package controls.throbber
{
	import flash.utils.Dictionary;
	
	import mx.core.UIComponent;
	import mx.managers.PopUpManager;
	
	public class ThrobberManager
	{
		// -------------- Private Variables ------------ //
		private static var _instance:ThrobberManager = null;
		private var _parent:UIComponent;
		private var throbber:Throbber;
		
		private var throbberCalls:Dictionary;
		private var throbberCount:int = 0;
		// -------------- Private Variables ------------ //
		
		public function ThrobberManager()
		{
			if(ThrobberManager._instance != null)
				throw new Error( "ThrobberManager is a Singleton: only one instance allowed." );
			
			throbber = new Throbber();
			throbberCalls = new Dictionary();
		}
		
		// ------------------ Singleton Implementation -------------- //
		public static function get instance():*
		{
			if(ThrobberManager._instance == null)
				ThrobberManager._instance = new ThrobberManager();
			return ThrobberManager._instance;
		}
		// ------------------ END Singleton Implementation --------------- //
		
		// ----------------- Accessors ---------------- //
		public function set parent(value:UIComponent):void
		{
			_parent = value;
			throbber.x = value.width / 2;
			throbber.y = value.height / 2;
		}
		public function get parent():UIComponent
		{
			return _parent;
		}
		// ----------------- END Accessors ---------------- //
		
		// ------------------ Throbber Functions ----------------- //
		public function startThrobber(id:String):void
		{
			if(!throbber.isRunning)
			{
				PopUpManager.addPopUp(throbber, parent, true);
				PopUpManager.centerPopUp(throbber);
				throbber.start();
			}
			if(!throbberCalls[id])
			{
				throbberCalls[id] = true;
				throbberCount ++;
			}
		}
		public function stopThrobber(id:String):void
		{
			if(throbberCalls[id])
			{ 
				throbberCalls[id] = false;
				throbberCount --;
			}
			
			if(throbberCount <= 0)
			{
				throbber.stop();
				PopUpManager.removePopUp(throbber);
			}
		}
		
		public function get isRunning():Boolean
		{
			return throbber.isRunning;
		}
		// ------------------ END Throbber Functions ----------------- //
	}
}